<template>
  <div class="market-overview">
    <!-- 市场统计概览 -->
    <div class="market-stats-section">
      <h2 class="section-title">
        <el-icon><TrendCharts /></el-icon>
        市场统计
      </h2>
      <div class="stats-grid" v-loading="statsLoading">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon market-cap">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">总市值</div>
              <div class="stat-value">{{ formatNumber(marketStats.totalMarketCap) }}</div>
              <div class="stat-change" :class="marketStats.totalMarketCapChange24h >= 0 ? 'positive' : 'negative'">
                {{ formatPercentage(marketStats.totalMarketCapChange24h) }}
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon volume">
              <el-icon><DataBoard /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">24h交易量</div>
              <div class="stat-value">{{ formatNumber(marketStats.totalVolume24h) }}</div>
              <div class="stat-change" :class="marketStats.totalVolumeChange24h >= 0 ? 'positive' : 'negative'">
                {{ formatPercentage(marketStats.totalVolumeChange24h) }}
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon btc-dominance">
              <el-icon><PieChart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">BTC市占率</div>
              <div class="stat-value">{{ marketStats.btcDominance }}%</div>
              <div class="stat-change" :class="marketStats.btcDominanceChange24h >= 0 ? 'positive' : 'negative'">
                {{ formatPercentage(marketStats.btcDominanceChange24h) }}
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon fear-greed">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">恐慌贪婪指数</div>
              <div class="stat-value">{{ marketStats.fearGreedIndex }}</div>
              <div class="stat-change fear-greed-level">{{ marketStats.fearGreedLevel }}</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 热门币种 -->
    <div class="hot-coins-section">
      <h2 class="section-title">
        <el-icon><Star /></el-icon>
        热门币种
      </h2>
      <el-card class="coins-table-card" v-loading="coinsLoading">
        <el-table :data="hotCoins" style="width: 100%" stripe>
          <el-table-column prop="marketCapRank" label="排名" width="80" align="center" />
          <el-table-column label="币种" width="200">
            <template #default="scope">
              <div class="coin-info">
                <img :src="scope.row.image" :alt="scope.row.name" class="coin-logo" />
                <div class="coin-details">
                  <div class="coin-name">{{ scope.row.name }}</div>
                  <div class="coin-symbol">{{ scope.row.symbol.toUpperCase() }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="价格" align="right">
            <template #default="scope">
              <div class="price-info">
                <div class="current-price">{{ formatPrice(scope.row.currentPrice) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="24h涨跌" align="right">
            <template #default="scope">
              <div class="price-change" :class="scope.row.priceChangePercentage24h >= 0 ? 'positive' : 'negative'">
                {{ formatPercentage(scope.row.priceChangePercentage24h) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="市值" align="right">
            <template #default="scope">
              <div class="market-cap">{{ formatNumber(scope.row.marketCap) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="24h交易量" align="right">
            <template #default="scope">
              <div class="volume">{{ formatNumber(scope.row.volume24h) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="7日走势" width="120" align="center">
            <template #default="scope">
              <div class="sparkline">
                <canvas :ref="'sparkline-' + scope.row.id" width="100" height="30"></canvas>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 市场分类 -->
    <div class="market-categories-section">
      <h2 class="section-title">
        <el-icon><Grid /></el-icon>
        市场分类
      </h2>
      <div class="categories-grid" v-loading="categoriesLoading">
        <el-card v-for="category in marketCategories" :key="category.id" class="category-card">
          <div class="category-header">
            <h3 class="category-name">{{ category.name }}</h3>
            <div class="category-change" :class="category.marketCapChange24h >= 0 ? 'positive' : 'negative'">
              {{ formatPercentage(category.marketCapChange24h) }}
            </div>
          </div>
          <div class="category-stats">
            <div class="category-stat">
              <div class="stat-label">市值</div>
              <div class="stat-value">{{ formatNumber(category.marketCap) }}</div>
            </div>
            <div class="category-stat">
              <div class="stat-label">24h交易量</div>
              <div class="stat-value">{{ formatNumber(category.volume24h) }}</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 恐慌贪婪指数历史 -->
    <div class="fear-greed-section">
      <h2 class="section-title">
        <el-icon><DataAnalysis /></el-icon>
        恐慌贪婪指数历史
      </h2>
      <el-card class="fear-greed-card" v-loading="fearGreedLoading">
        <div class="fear-greed-chart">
          <canvas ref="fearGreedChart" width="800" height="300"></canvas>
        </div>
        <div class="fear-greed-legend">
          <div class="legend-item extreme-fear">极度恐慌 (0-24)</div>
          <div class="legend-item fear">恐慌 (25-49)</div>
          <div class="legend-item neutral">中性 (50-74)</div>
          <div class="legend-item greed">贪婪 (75-100)</div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { 
  TrendCharts, 
  Money, 
  DataBoard, 
  PieChart, 
  Warning, 
  Star, 
  Grid,
  DataAnalysis
} from '@element-plus/icons-vue'
import {
  fetchMarketStats,
  fetchHotCoins,
  fetchMarketCategories,
  fetchFearGreedHistory,
  formatNumber,
  formatPrice,
  formatPercentage,
  type MarketStats,
  type HotCoin,
  type MarketCategory,
  type FearGreedHistory
} from '@/mock/marketData'

// 响应式数据
const marketStats = ref<MarketStats>({
  totalMarketCap: 0,
  totalMarketCapChange24h: 0,
  totalVolume24h: 0,
  totalVolumeChange24h: 0,
  btcDominance: 0,
  btcDominanceChange24h: 0,
  ethDominance: 0,
  ethDominanceChange24h: 0,
  activeCryptocurrencies: 0,
  totalExchanges: 0,
  fearGreedIndex: 0,
  fearGreedLevel: ''
})

const hotCoins = ref<HotCoin[]>([])
const marketCategories = ref<MarketCategory[]>([])
const fearGreedHistory = ref<FearGreedHistory[]>([])

// 加载状态
const statsLoading = ref(false)
const coinsLoading = ref(false)
const categoriesLoading = ref(false)
const fearGreedLoading = ref(false)

// 图表引用
const fearGreedChart = ref<HTMLCanvasElement>()

// 加载数据
const loadMarketStats = async () => {
  statsLoading.value = true
  try {
    marketStats.value = await fetchMarketStats()
  } catch (error) {
    console.error('Failed to load market stats:', error)
  } finally {
    statsLoading.value = false
  }
}

const loadHotCoins = async () => {
  coinsLoading.value = true
  try {
    hotCoins.value = await fetchHotCoins(10)
    await nextTick()
    drawSparklines()
  } catch (error) {
    console.error('Failed to load hot coins:', error)
  } finally {
    coinsLoading.value = false
  }
}

const loadMarketCategories = async () => {
  categoriesLoading.value = true
  try {
    marketCategories.value = await fetchMarketCategories()
  } catch (error) {
    console.error('Failed to load market categories:', error)
  } finally {
    categoriesLoading.value = false
  }
}

const loadFearGreedHistory = async () => {
  fearGreedLoading.value = true
  try {
    fearGreedHistory.value = await fetchFearGreedHistory(7)
    await nextTick()
    drawFearGreedChart()
  } catch (error) {
    console.error('Failed to load fear greed history:', error)
  } finally {
    fearGreedLoading.value = false
  }
}

// 绘制走势图
const drawSparklines = () => {
  hotCoins.value.forEach(coin => {
    const canvas = document.querySelector(`[ref="sparkline-${coin.id}"]`) as HTMLCanvasElement
    if (!canvas) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    const data = coin.sparklineIn7d
    const width = canvas.width
    const height = canvas.height
    const padding = 5

    ctx.clearRect(0, 0, width, height)

    if (data.length < 2) return

    const min = Math.min(...data)
    const max = Math.max(...data)
    const range = max - min || 1

    // 设置线条样式
    ctx.strokeStyle = coin.priceChangePercentage24h >= 0 ? '#67C23A' : '#F56C6C'
    ctx.lineWidth = 1.5
    ctx.lineCap = 'round'
    ctx.lineJoin = 'round'

    ctx.beginPath()
    data.forEach((value, index) => {
      const x = padding + (index / (data.length - 1)) * (width - 2 * padding)
      const y = height - padding - ((value - min) / range) * (height - 2 * padding)
      
      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
    })
    ctx.stroke()
  })
}

// 绘制恐慌贪婪指数图表
const drawFearGreedChart = () => {
  const canvas = fearGreedChart.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  if (!ctx) return

  const width = canvas.width
  const height = canvas.height
  const padding = 40

  ctx.clearRect(0, 0, width, height)

  if (fearGreedHistory.value.length < 2) return

  const data = fearGreedHistory.value.reverse()
  const maxValue = 100
  const minValue = 0

  // 绘制背景区域
  const drawZone = (startY: number, endY: number, color: string) => {
    ctx.fillStyle = color
    ctx.fillRect(padding, startY, width - 2 * padding, endY - startY)
  }

  // 绘制恐慌贪婪区域背景
  drawZone(padding, padding + (height - 2 * padding) * 0.25, 'rgba(245, 108, 108, 0.1)') // 极度恐慌
  drawZone(padding + (height - 2 * padding) * 0.25, padding + (height - 2 * padding) * 0.5, 'rgba(255, 192, 105, 0.1)') // 恐慌
  drawZone(padding + (height - 2 * padding) * 0.5, padding + (height - 2 * padding) * 0.75, 'rgba(255, 235, 59, 0.1)') // 中性
  drawZone(padding + (height - 2 * padding) * 0.75, height - padding, 'rgba(103, 194, 58, 0.1)') // 贪婪

  // 绘制网格线
  ctx.strokeStyle = '#E4E7ED'
  ctx.lineWidth = 1
  for (let i = 0; i <= 4; i++) {
    const y = padding + (i / 4) * (height - 2 * padding)
    ctx.beginPath()
    ctx.moveTo(padding, y)
    ctx.lineTo(width - padding, y)
    ctx.stroke()
  }

  // 绘制数据线
  ctx.strokeStyle = '#409EFF'
  ctx.lineWidth = 2
  ctx.beginPath()

  data.forEach((item, index) => {
    const x = padding + (index / (data.length - 1)) * (width - 2 * padding)
    const y = height - padding - ((item.value - minValue) / (maxValue - minValue)) * (height - 2 * padding)
    
    if (index === 0) {
      ctx.moveTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
  })
  ctx.stroke()

  // 绘制数据点
  ctx.fillStyle = '#409EFF'
  data.forEach((item, index) => {
    const x = padding + (index / (data.length - 1)) * (width - 2 * padding)
    const y = height - padding - ((item.value - minValue) / (maxValue - minValue)) * (height - 2 * padding)
    
    ctx.beginPath()
    ctx.arc(x, y, 3, 0, 2 * Math.PI)
    ctx.fill()
  })

  // 绘制Y轴标签
  ctx.fillStyle = '#606266'
  ctx.font = '12px Arial'
  ctx.textAlign = 'right'
  for (let i = 0; i <= 4; i++) {
    const value = 100 - (i * 25)
    const y = padding + (i / 4) * (height - 2 * padding)
    ctx.fillText(value.toString(), padding - 10, y + 4)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadMarketStats()
  loadHotCoins()
  loadMarketCategories()
  loadFearGreedHistory()
})
</script>

<style scoped>
.market-overview {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

/* 市场统计样式 */
.market-stats-section {
  margin-bottom: 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.market-cap {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.volume {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.btc-dominance {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.fear-greed {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-change {
  font-size: 12px;
  font-weight: 500;
}

.stat-change.positive {
  color: #67C23A;
}

.stat-change.negative {
  color: #F56C6C;
}

.fear-greed-level {
  color: #409EFF !important;
  font-weight: 600;
}

/* 热门币种样式 */
.hot-coins-section {
  margin-bottom: 32px;
}

.coins-table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.coin-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.coin-logo {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.coin-details {
  flex: 1;
}

.coin-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.coin-symbol {
  font-size: 12px;
  color: #909399;
}

.current-price {
  font-weight: 600;
  color: #303133;
}

.price-change {
  font-weight: 600;
}

.price-change.positive {
  color: #67C23A;
}

.price-change.negative {
  color: #F56C6C;
}

.market-cap, .volume {
  color: #606266;
  font-size: 14px;
}

.sparkline {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 市场分类样式 */
.market-categories-section {
  margin-bottom: 32px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.category-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.category-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.category-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.category-change {
  font-size: 14px;
  font-weight: 600;
}

.category-change.positive {
  color: #67C23A;
}

.category-change.negative {
  color: #F56C6C;
}

.category-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.category-stat {
  text-align: center;
}

.category-stat .stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.category-stat .stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 恐慌贪婪指数样式 */
.fear-greed-section {
  margin-bottom: 32px;
}

.fear-greed-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.fear-greed-chart {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.fear-greed-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  flex-wrap: wrap;
}

.legend-item {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.legend-item.extreme-fear {
  background: rgba(245, 108, 108, 0.2);
  color: #F56C6C;
}

.legend-item.fear {
  background: rgba(255, 192, 105, 0.2);
  color: #E6A23C;
}

.legend-item.neutral {
  background: rgba(255, 235, 59, 0.2);
  color: #E6A23C;
}

.legend-item.greed {
  background: rgba(103, 194, 58, 0.2);
  color: #67C23A;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .market-overview {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .categories-grid {
    grid-template-columns: 1fr;
  }
  
  .fear-greed-legend {
    gap: 12px;
  }
  
  .stat-content {
    gap: 12px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 20px;
  }
}
</style>
